<?php

namespace App\Admin\Repositories;

use App\library\services\NewHouseService;
use App\Models\SecondHandHouse as Model;
use Dcat\Admin\Form;
use Dcat\Admin\Repositories\EloquentRepository;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;

class SecondHandHouse extends EloquentRepository
{
    /**
     * Model.
     *
     * @var string
     */
    protected $eloquentClass = Model::class;

    public function store(Form $form)
    {
        $result = null;


        DB::transaction(function () use ($form, &$result) {
            $model = $this->model();

            $updates = $form->updates();

            [$relations, $relationKeyMap] = $this->getRelationInputs($model, $updates);

            if ($relations) {
                $updates = Arr::except($updates, array_keys($relationKeyMap));
            }
            $updates['image'] = $updates['images'][0];
            $updates['images'] =  implode("&",$updates['images']);
            $res = NewHouseService::geocoding($updates['address']);
            $updates['latitude'] = $res['result']['location']['lat'];
            $updates['longitude'] = $res['result']['location']['lng'];
            foreach ($updates as $column => $value) {
                $model->setAttribute($column, $value);
            }

            $result = $model->save();

            $this->updateRelation($form, $model, $relations, $relationKeyMap);
        });

        return $this->model()->getKey();
    }
}
